/*
 *    Copyright (C) 2011-2012 Hai Bison
 *
 *    See the file LICENSE at the root directory of this project for copying
 *    permission.
 */

/*
 * DialogPreferences.java
 *
 * Created on Sep 10, 2011, 3:19:09 PM
 */
package group.pals.mailgate;

import group.pals.mailgate.preferences.ui.PanelPreferencesConnection;
import group.pals.mailgate.preferences.ui.PanelPreferencesView;
import group.pals.mailgate.preferences.ui.PanelPreferencesEmailAccounts;
import group.pals.mailgate.preferences.ui.PanelPreferencesEmailProviders;
import group.pals.mailgate.preferences.ui.PanelPreferencesNotification;
import group.pals.mailgate.preferences.ui.PanelPreferencesSecurity;
import group.pals.mailgate.preferences.ui.PanelPreferencesAutoUpdate;
import group.pals.mailgate.ui.IPreferences;
import group.pals.mailgate.preferences.Preferences;
import java.awt.event.ActionEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.AbstractAction;
import javax.swing.JDialog;
import javax.swing.JTabbedPane;

/**
 *
 * @author Hai Bison
 */
public final class DialogPreferences extends javax.swing.JDialog implements IPreferences {

    private final Preferences _Preferences;

    /** Creates new form DialogPreferences */
    public DialogPreferences(java.awt.Frame parent, boolean modal) {
        super(parent, modal);

        initComponents();

        this._Preferences = Preferences.getInstance();

        setLocationRelativeTo(parent);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setTitle("Preferences");
        setResizable(false);

        tabbedPaneMain.addTab("Security", new PanelPreferencesSecurity());
        tabbedPaneMain.addTab("E-mail Accounts", new PanelPreferencesEmailAccounts());
        tabbedPaneMain.addTab("E-mail Providers", new PanelPreferencesEmailProviders());
        tabbedPaneMain.addTab("Connection", new PanelPreferencesConnection());
        tabbedPaneMain.addTab("View", new PanelPreferencesView());
        tabbedPaneMain.addTab("Notification", new PanelPreferencesNotification());
        tabbedPaneMain.addTab("Auto Update", new PanelPreferencesAutoUpdate());

        initActions();
        initListeners();
        initUI();

        loadPreferences();
    }

    private void initActions() {
        actionOk = new ActionOk();
        actionCancel = new ActionCancel();

        btnOk.setAction(actionOk);
        btnCancel.setAction(actionCancel);
    }

    private void initListeners() {
        tabbedPaneMain.addMouseWheelListener(new MouseWheelListener() {

            @Override
            public void mouseWheelMoved(MouseWheelEvent e) {
                if (!(e.getComponent() instanceof JTabbedPane)) {
                    return;
                }

                int iSelected = tabbedPaneMain.getSelectedIndex();
                if (iSelected < 0) {
                    if (tabbedPaneMain.getTabCount() > 0) {
                        tabbedPaneMain.setSelectedIndex(0);
                    }
                    return;
                }

                if (e.getY() > tabbedPaneMain.getComponentAt(iSelected).getY()) {
                    return;
                }

                if (e.getWheelRotation() < 0) {
                    if (iSelected > 0) {
                        tabbedPaneMain.setSelectedIndex(--iSelected);
                    }
                } else {
                    if (iSelected < tabbedPaneMain.getTabCount() - 1) {
                        tabbedPaneMain.setSelectedIndex(++iSelected);
                    }
                }
            }
        });
    }

    private void initUI() {
        //ERROR
        //tabbedPaneMain.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tabbedPaneMain = new javax.swing.JTabbedPane();
        btnOk = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        btnOk.setText("jButton1");

        btnCancel.setText("jButton2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(tabbedPaneMain, javax.swing.GroupLayout.DEFAULT_SIZE, 644, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnOk)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tabbedPaneMain, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancel)
                    .addComponent(btnOk))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
//  /**
//   * @param args the command line arguments
//   */
//  public static void main(String args[]) {
//    /* Set the Nimbus look and feel */
//    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//     */
//    try {
//      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//        if ("Nimbus".equals(info.getName())) {
//          javax.swing.UIManager.setLookAndFeel(info.getClassName());
//          break;
//        }
//      }
//    } catch (ClassNotFoundException ex) {
//      java.util.logging.Logger.getLogger(DialogPreferences.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//    } catch (InstantiationException ex) {
//      java.util.logging.Logger.getLogger(DialogPreferences.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//    } catch (IllegalAccessException ex) {
//      java.util.logging.Logger.getLogger(DialogPreferences.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//      java.util.logging.Logger.getLogger(DialogPreferences.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//    }
//    //</editor-fold>
//
//    /* Create and display the dialog */
//    java.awt.EventQueue.invokeLater(new Runnable() {
//
//      public void run() {
//        DialogPreferences dialog = new DialogPreferences(new javax.swing.JFrame(), true);
//        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
//
//          @Override
//          public void windowClosing(java.awt.event.WindowEvent e) {
//            System.exit(0);
//          }
//        });
//        dialog.setVisible(true);
//      }
//    });
//  }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOk;
    private javax.swing.JTabbedPane tabbedPaneMain;
    // End of variables declaration//GEN-END:variables

    /*----------------------------------------------------------------------------
     * IPreferences
     */
    public void loadPreferences() {
        for (int i = 0; i < tabbedPaneMain.getComponentCount(); i++) {
            if (tabbedPaneMain.getComponentAt(i) instanceof IPreferences) {
                IPreferences ip = (IPreferences) tabbedPaneMain.getComponentAt(i);
                ip.loadPreferences();
            }
        }
    }

    public boolean storePreferences(boolean prepare) {
        //first, check user's input values
        for (int i = 0; i < tabbedPaneMain.getComponentCount(); i++) {
            if (tabbedPaneMain.getComponentAt(i) instanceof IPreferences) {
                IPreferences ip = (IPreferences) tabbedPaneMain.getComponentAt(i);
                if (!ip.storePreferences(true)) {
                    tabbedPaneMain.setSelectedIndex(i);
                    return false;
                }
            }
        }

        //then, store preferences
        for (int i = 0; i < tabbedPaneMain.getComponentCount(); i++) {
            if (tabbedPaneMain.getComponentAt(i) instanceof IPreferences) {
                IPreferences ip = (IPreferences) tabbedPaneMain.getComponentAt(i);
                if (!ip.storePreferences(false)) {
                    tabbedPaneMain.setSelectedIndex(i);
                    return false;
                }
            }
        }

        _Preferences.store();
        return true;
    }

    public void closeResources() {
        //do nothing
    }

    @Override
    public void dispose() {
        for (int i = 0; i < tabbedPaneMain.getComponentCount(); i++) {
            if (tabbedPaneMain.getComponentAt(i) instanceof IPreferences) {
                IPreferences ip = (IPreferences) tabbedPaneMain.getComponentAt(i);
                ip.closeResources();
            }
        }
        tabbedPaneMain.removeAll();
        closeResources();
        System.gc();

        super.dispose();
    }
    /*----------------------------------------------------------------------------
     * ACTIONS
     */

    /*----------------------------------------------------------------------------
     * ActionOk
     */
    private ActionOk actionOk;

    private class ActionOk extends AbstractAction {

        public ActionOk() {
            super("Ok");
        }

        public void actionPerformed(ActionEvent e) {
            if (storePreferences(false)) {
                dispose();
            }
        }
    }
    /*----------------------------------------------------------------------------
     * ActionCancel
     */
    private ActionCancel actionCancel;

    private class ActionCancel extends AbstractAction {

        public ActionCancel() {
            super("Cancel");
        }

        public void actionPerformed(ActionEvent e) {
            dispose();
        }
    }
}
